#pragma once
#include <memory>

#include "socket.hpp"
#include "connection.hpp"
#include "common.hpp"
#include "netservice.hpp"
#include "calculator.hpp"

/*负责listen的链接的模块*/
class listener :public connection{
public:
    listener(uint16_t port):_port(port){
        listen_sock=std::make_shared<TcpSocket>();
        listen_sock->BulitListenSocket(_port);
        _sockfd=listen_sock->Fd();
        _event=EPOLLIN|EPOLLET;
        SetNonBlock(_sockfd);//将对应的fd，设为非阻塞状态
    }
    virtual void _recv() override{
        while(true)
        {
            //获取新的连接(与对端主机进行网络通信的链接)
            int errorcode;
            inetaddr client;
            int fd=listen_sock->accept(&errorcode,&client);
            if(fd>=0){
                LOG(INFO)<<"get a new client:"<<client.addr();
                connect_t peer=make_NetConnection(fd,EPOLLIN|EPOLLET);//
                peer->setaddr(client);
                peer->RegistHandle(execute);
                _own->insert(peer);//将链接添加到reactor中
            }
            else {
                if(errorcode==EAGAIN||errorcode==EWOULDBLOCK){
                    //说明此时没有新的连接发送了，结束对listen的读取
                    LOG(DEBUG)<<"No more connection";
                    break;
                }
                else if(errorcode==EINTR){
                    //由于中断信号暂停了读取，重新开始读取
                    continue;
                }
                else {
                    _except();//对于异常的处理方案
                    return;
                }
            }
        }
    }

    virtual void _send() override{
        //listen套接字不能写入
    }

    virtual void _except() override{
        //异常处理，根据需求来
    }

    int FD(){return listen_sock->Fd();} 
    
    ~listener(){
        listen_sock->closeSocket();
    }
private:
    uint16_t _port;
    std::shared_ptr<Socket> listen_sock;
};

connect_t make_Listener(uint16_t port){
    return std::make_shared<listener>(port);
}